public with sharing class PriceConsultationController {

	public Boolean isErr {get;private set;}
	public String  msg {get;private set;}
	public Boolean isSuccess {get;private set;}

	public String  backId {get;private set;}

	public String dataJson {get;private set;}
	public String paramJson {get;set;}
	public String searchJson {get; set;}

	public String cate1combox {get;set;}
  	public String cate2combox {get;set;}
  	public String cate3combox {get;set;}

	public PriceConsultation__c pc {get;set;}

	public Boolean isNew ;
	public Map<String,String>companyMap;

	public String companycombox {get;private set;}
  	public String accountlevelcombox {get;private set;}
  	public Boolean isCouldFindOverseaProduct;
  	public String sealflag ;

    public PriceConsultationController() {
        pc = new PriceConsultation__c();
    	backId = System.currentPageReference().getParameters().get('id');
    }
    public void init (){
    	if(backId == null){
    		setErr('页面打开错误 !');
    		return;
    	}

    	companyMap = new Map<String,String>();
    	Map<String,String > tmpMap = new Map<String,String >();
        for(String com : Label.ShortCompanyName.split(',',-1)){
            List<String> cs = com.split('-',-1);
            if(cs != null && cs.size() > 1)companyMap.put(cs[0],cs[1]);
            if(cs != null && cs.size() > 1)tmpMap.put(cs[1],cs[1]);
        }

        cate1combox = getOptsFromProduct('Category1__c');
        cate2combox = getOptsFromProduct('Category2__c');
        cate3combox = getOptsFromProduct('Category3__c');
    	companycombox = getOptMap(companyMap,true );

        accountlevelcombox = getOptMap(ImportObject.getPicklistValues('PriceConsultationList__c', 'AccountLevel__c', true),true);
        for(String com : Label.ShortCompanyName.split(',',-1)){
            List<String> cs = com.split('-',-1);
            if(cs != null && cs.size() > 1)companyMap.put(cs[0],cs[1]);
        }
    	if(Id.valueOf(backId).getSobjectType() == Opportunity.SObjectType){
    		isNew = true;
    		pc.Opportunitie__c = backId;
    		pc.Status__c = '草稿中';

    	}else if(Id.valueOf(backId).getSobjectType() == PriceConsultation__c.SObjectType ){
    		isNew = false;
    		pc = [select Id,AnswerTime__c ,Opportunitie__c,Status__c from PriceConsultation__c where Id=:backId];
    	}else{
    		setErr('页面打开错误');
    	}
    	if(pc.Status__c == '审批中' || pc.Status__c == '已批准'){
    		setErr('价格咨询状态为'+pc.Status__c +' ,不能修改!');
    		return;
    	}
    	User u = [select Id ,Profile.Name ,SubCompany__c from User where Id=:UserInfo.getUserId()];

    	Map<String,String> cm = ImportObject.getPicklistValues('PriceConsultationList__c','Company__c',false);
        if(cm.get(u.SubCompany__c) == null)setErr('公司编码维护错误!请联系管理员维护!');
        sealflag = 'Y-'+cm.get(u.SubCompany__c);


        isCouldFindOverseaProduct = u.Profile.Name.contains('海外') ? true : false;


    }
    public String getOptsFromProduct(String cate ){

      Map<String,String> tmpMap = new Map<String,String>();

        for (AggregateResult arg  :Database.query('select '+cate +'  from Product__c group by '+cate ) ){
            tmpMap.put(String.valueOf(arg.get(cate)), String.valueOf(arg.get(cate)));
        }
        return getOptMap(tmpMap,false);
    }
    public String getOptMap(Map<String,String> opts,Boolean isMuti ){
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', '200');
      
      cooMap.put('separator', ';');
      cooMap.put('limitToList', 'true');
      if(isMuti)cooMap.put('multiple','true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }
    //获取明细
    public void getDetails(){
    	if(Id.valueOf(backId).getSobjectType() == PriceConsultation__c.SObjectType){

    		getProductFromPriceConsultationList();

    	}else if(Id.valueOf(backId).getSobjectType() == Opportunity.SObjectType){

    		getProductFromIntentProduct();
    	}

    }

    //保存
    public void save(){

    	 msg = '';
	     List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(paramJson, 'UTF-8'));
	     if(resList.size() == 0){
	        msg = '保存失败,没有数据!';
	        return;
	    }
	    //回写意向产品?

	    List<PriceConsultationList__c>   pList = new List<PriceConsultationList__c>();
	    for (Object res : resList) {
	        Map<String ,Object> o = (Map<String ,Object> )res;
	        PriceConsultationList__c pcl = new PriceConsultationList__c();
	        String productId = String.valueOf(o.get('productId'));

	        if(productId == null){
	          msg += String.valueOf(o.get('productName'))+'  数据异常!';
	          break;
	        }

	        pcl.Product__c = getStringValue(o.get('productId'));
	        pcl.Authorization__c = getStringValue(o.get('autharea'));
	        pcl.AccountLevel__c = getStringValue(o.get('accoutlevel'));
	        pcl.IsFromCatalog__c = Boolean.valueOf(o.get('isFromCatalog'));
	        pcl.Company__c = getStringValue(o.get('company'));
	        pcl.ProcurementCosts__c = getDecimalValue(o.get('cost'));
	        pList.add(pcl);

	    }

	    if(msg.length() > 0)return;
	    SavePoint sp = Database.setSavepoint();
	    try {
	        if(isNew) insert pc;
	        for (PriceConsultationList__c pcl : pList) {
	        	pcl.PriceConsultation__c = pc.Id;
	        }

	        if(pList.size() > 0){
	        	delete [select Id from PriceConsultationList__c where  PriceConsultation__c =:pc.Id];
	        	insert pList;
	        	isSuccess = true;
	        	msg = '保存成功!';
	        	backId = pc.Id;
	        } 

	    }catch (Exception e) {
	        Database.rollback(sp);
	        if(isNew)pc.Id = null;

	        

	        msg = '保存失败:'+e.getMessage() + e.getStackTraceString();
	    }
	    


    }
    private String getStringValue(Object o ){
    	if(o == null) return null;
    	return String.valueOf(o).trim();
    }
    private Decimal getDecimalValue(Object o){
    	String s = getStringValue(o);
    	if(s == null || s.length() == 0 ) return null;
    	return Decimal.valueOf(s);
    }
    //选择产品
    public void getProducts (){
    	 Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(paramJson, 'UTF-8'));
	      String sql = 'select Id ,Name ,ProductName__c ,Unit__c, Brand__c,Spec__c,Model__c,SerialNo__c ,SealCompany__c ,NCCode__c,Category1__c,Category2__c,Category0__c  from Product__c where Name != null ';
	      
	      if(!isCouldFindOverseaProduct) sql += ' and  Overseasproducts__c != true  ';

	      if(String.isBlank(String.valueOf(searchMap.get('name'))) == false){
	        sql += ' and ProductName__c like \'%'+String.valueOf(searchMap.get('name'))+'%\'';
	      }
	      if(String.isBlank(String.valueOf(searchMap.get('brand'))) == false){
	        sql += ' and Brand__c like \'%'+String.valueOf(searchMap.get('brand'))+'%\'';
	      }
	      if(String.isBlank(String.valueOf(searchMap.get('serialno'))) == false){
	        sql += ' and SerialNo__c like \'%'+String.valueOf(searchMap.get('serialno'))+'%\'';
	      }
	      if(String.isBlank(String.valueOf(searchMap.get('model'))) == false){
	        sql += ' and Model__c like \'%'+String.valueOf(searchMap.get('model'))+'%\'';
	      }
	      if(String.isBlank(String.valueOf(searchMap.get('nccode'))) == false){
	        sql += ' and NCCode__c like \'%'+String.valueOf(searchMap.get('nccode'))+'%\'';
	      }
	      if(String.isBlank(String.valueOf(searchMap.get('cate1'))) == false){
	        sql += ' and Category1__c like \'%'+String.valueOf(searchMap.get('cate1'))+'%\'';
	      }
	      if(String.isBlank(String.valueOf(searchMap.get('cate2'))) == false){
	        sql += ' and Category2__c like \'%'+String.valueOf(searchMap.get('cate2'))+'%\'';
	      }
	      if(String.isBlank(String.valueOf(searchMap.get('cate3'))) == false){
	        sql += ' and Category3__c like \'%'+String.valueOf(searchMap.get('cate3'))+'%\'';
	      }
	    

	      sql += '  Limit 300 ';
	      List<PriceConsultationBean> tmp = new List<PriceConsultationBean>();
	      for(Product__c p : Database.query(sql)){
	        if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)))tmp.add(new PriceConsultationBean(p));
	      }

	      searchJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');
    }
    ///询价明细
    private void getProductFromPriceConsultationList(){
    	 List<PriceConsultationBean> tmp = new List<PriceConsultationBean>();

    	for (PriceConsultationList__c pcl  :[select Id ,Product__c ,Authorization__c,Product__r.Name,Product__r.ProductName__c,
    			Product__r.Unit__c,Product__r.Brand__c,Product__r.Model__c,Product__r.NCCode__c,AccountLevel__c,
    			Product__r.Spec__c,ProcurementCosts__c,ProjectsExpected__c,Product__r.Category1__c,IsFromCatalog__c,Company__c
    			from PriceConsultationList__c where PriceConsultation__c =:backId] ) {
    			tmp.add(new PriceConsultationBean(pcl));
    	}
    	dataJson = EncodingUtil.urlEncode(JSon.serialize(tmp), 'UTF-8');
    }
    ///从意向产品中带入明细到这里
    private void getProductFromIntentProduct(){
    	List<PriceConsultationBean> tmp = new List<PriceConsultationBean>();
    	for (IntentProduct__c ip : [select Id ,Product__c,Product__r.Unit__c,Product__r.Brand__c,Product__r.Model__c,Product__r.NCCode__c,
    		Product__r.Spec__c,Product__r.Category1__c,Product__r.Name,Product__r.ProductName__c,IsFromCatalog__c  from IntentProduct__c
    		where Opportunity__c =:backId]) {
    		tmp.add(new PriceConsultationBean(ip));

    	}
    	dataJson = EncodingUtil.urlEncode(JSon.serialize(tmp), 'UTF-8');
    }
    public void setNil(){
    	dataJson = '[]';
    	searchJson = '[]';
    	paramJson = '';
    }

    private void setErr(String meassage){
    	isErr = true;
    	ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,meassage));
    }


    public Class PriceConsultationBean{

    	public String productName ;
    	public String productId;
    	public String brand ;
    	public String spec ;
    	public String model ;
    	public String unit ;
    	public String nccode ; 
    	public String autharea ; 
    	public String productLine;
    	public Decimal cost ;
    	public Boolean isFromCatalog;
    	public String company;
    	public String accoutlevel ; 
    	public String cate1;
    	public String cate2 ; 
    	public String cate0 ; 



    	public PriceConsultationBean(PriceConsultationList__c pcl ){
    		productId = pcl.Product__c;
    		productName = pcl.Product__r.ProductName__c == null ? pcl.Product__r.Name :pcl.Product__r.ProductName__c ;
    		brand = pcl.Product__r.Brand__c; 
    		spec = pcl.Product__r.Spec__c;
    		model = pcl.Product__r.Model__c;
    		unit = pcl.Product__r.Unit__c;
    		nccode = pcl.Product__r.NCCode__c;
    		productLine = pcl.Product__r.Category1__c;
    		autharea  = pcl.Authorization__c;
    		//isbackwrite = pcl.WhetherWriteBack__c;
    		cost = pcl.ProcurementCosts__c;
    		//config = pcl.ConfigurationRequirement__c;
    		isFromCatalog = pcl.IsFromCatalog__c;
    		company = pcl.Company__c;
    		accoutlevel = pcl.AccountLevel__c;

    	}
    	public PriceConsultationBean(IntentProduct__c pcl){
    		productId = pcl.Product__c;
    		productName = pcl.Product__r.ProductName__c == null ? pcl.Product__r.Name :pcl.Product__r.ProductName__c ;
    		brand = pcl.Product__r.Brand__c; 
    		spec = pcl.Product__r.Spec__c;
    		model = pcl.Product__r.Model__c;
    		unit = pcl.Product__r.Unit__c;
    		nccode = pcl.Product__r.NCCode__c;
    		productLine = pcl.Product__r.Category1__c;
    		isFromCatalog = pcl.IsFromCatalog__c;
    		//company = pcl.Company__c;
    		//accoutlevel = pcl.AccountLevel__c;

    	}
    	public PriceConsultationBean(Product__c pcl){
    		productId = pcl.Id ;
    		productName = pcl.ProductName__c == null ? pcl.Name :pcl.ProductName__c ;
    		brand = pcl.Brand__c; 
    		spec = pcl.Spec__c;
    		model = pcl.Model__c;
    		unit = pcl.Unit__c;
    		nccode = pcl.NCCode__c;
    		productLine = pcl.Category1__c;
    		isFromCatalog = false;

    		cate0 = pcl.Category0__c;
    		cate1 = pcl.Category1__c;
    		cate2 = pcl.Category2__c;

    		//company = pcl.Company__c;
    		//accoutlevel = pcl.AccountLevel__c;

    	}


    	private String getCompanystring (String coms ,Map<String,String> companys){
	        String c = '';
	        if(coms == null) return c;
	          for (String cs  :coms.split(';') ) {
	            if(companys.containsKey(cs)){
	              c += companys.get(cs)+';';
	            }
         	}
          	return c;

      	}

    }
}